<template>
  <div class="UnionMessage">
    <div class="searchBox">
      <div>
        <el-input placeholder="请输入内容" clearable v-model="title">
          <template slot="prepend">标题</template>
        </el-input>
        <el-date-picker
          v-model="timeArr"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="timeOptions"
          value-format="yyyy-MM-dd"
          @change="focusA"
        >
        </el-date-picker>
        <el-button style="margin-left: 10px" class="btn" @click="search"
          >搜索</el-button
        >
      </div>
      <el-button type="success" @click="add" plain>新增消息</el-button>
    </div>
    <el-radio-group v-model="type" fill="#7b94d8" @change="search">
      <el-radio-button label="1">未发送</el-radio-button>
      <el-radio-button label="2">已发送</el-radio-button>
      <!-- <el-radio-button label="3">结算记录</el-radio-button> -->
    </el-radio-group>
    <el-card>
      <el-table
        :data="tableData"
        style="width: 100%; margin-top: 10px"
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <template slot="empty">
          <el-empty :image-size="200"></el-empty>
        </template>
        <el-table-column prop="create_time" label="创建时间"> </el-table-column>
        <el-table-column prop="title" label="主标题"> </el-table-column>
        <el-table-column prop="union_type" label="接收对象"> </el-table-column>
        <el-table-column prop="id" label="正文">
          <template slot-scope="scope">
            <el-button
              type="primary"
              plain
              size="small"
              @click="look(scope.row)"
              >查看</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="id" v-if="type == 1" key="2332" label="操作">
          <template slot-scope="scope">
            <el-button
              type="success"
              plain
              size="small"
              @click="nowSend(scope.row.id, '1')"
              >立即发送</el-button
            >
            <el-button
              type="danger"
              plain
              size="small"
              @click="del(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="total"
        :page.sync="page"
        :limit.sync="pageSize"
        @pagination="getList"
      />
    </el-card>
    <el-dialog title="新增消息" :visible.sync="dialogVisible" width="50%">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="主题" prop="title1">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- <el-input v-model="form.content"></el-input> -->
          <div
            id="websiteEditorElem"
            style="height: 300px; background: #ffffff"
          ></div>
        </el-form-item>
        <div style="height: 100px"></div>
        <el-form-item label="工会选择" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="1">全体工会</el-radio>
            <el-radio label="2">指定工会</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="指定工会编号" v-if="form.type == 2" prop="ids">
          <el-input v-model="form.ids"></el-input>
          <span>多个工会用英文逗号,隔开</span>
        </el-form-item>
        <el-form-item
          label="发送时间"
          prop="sendType"
          @change="form.sendTime = ''"
        >
          <el-radio-group v-model="form.sendType">
            <el-radio label="1">立即发送</el-radio>
            <el-radio label="2">指定时间</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="form.sendType == 2"
          label="选择发送时间"
          prop="sendTime"
        >
          <!-- <el-radio-group v-model="form.sendTime">
            <el-radio label="1">立即发送</el-radio>
            <el-radio label="2">指定时间</el-radio>
          </el-radio-group> -->
          <el-date-picker
            v-model="form.sendTime"
            type="datetime"
            value-format="timestamp"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="submit">提 交</el-button>
      </span>
    </el-dialog>
    <el-dialog title="内容详情" :visible.sync="dialogVisible1" width="50%">
      <div v-html="html"></div>
    </el-dialog>
  </div>
</template>

<script>
import E from "wangeditor";
import { client } from "@/utils/oss.js";
import { ossToken } from "@/api/NotificationManagement";
import {
  AdminUnionMessageList,
  AdminUnionPushMessage,
  AdminUnionMessageSendUnionMessage,
  AdminUnionMessageDelUnionMessage,
} from "@/api/UnionManagement";
export default {
  data() {
    return {
      title: "",
      type: "1",
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 10,
      timeArr: [],
      startDate: "",
      endDate: "",
      timeOptions: {
        disabledDate(platformValue) {
          return platformValue.getTime() > Date.now() - 8.64e6;
        },
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      dialogVisible: false,
      form: {
        title: "",
        content: "",
        type: "1",
        ids: "",
        sendType: "1",
        sendTime: "",
      },
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "change" }],
      },
      //富文本
      editor: "",
      html: "",
      dialogVisible1: false,
    };
  },
  methods: {
    //选着时间
    focusA(time) {
      if (!this.timeArr) {
        this.timeArr = [];
      }
      this.startDate = this.timeArr[0];
      this.endDate = this.timeArr[1];
    },
    search() {
      this.page = 1;
      this.getList();
    },
    async getList() {
      let state;
      if (this.type == 1) {
        state = 0;
      } else {
        state = 1;
      }
      const res = await AdminUnionMessageList({
        title: this.title,
        startTime: this.startDate,
        endTime: this.endDate,
        page: this.page,
        pageSize: this.pageSize,
        // type: this.type,
        state,
      });
      if (res.code == 0) {
        this.total = parseInt(res.data.total);
        this.tableData = res.data.list;
      }
    },
    add() {
      this.dialogVisible = true;
      this.$nextTick(async () => {
        if (this.editor == "") {
          await ossToken({
            type: 0,
          }).then((res) => {
            if (res.code == 0) {
              this.dataObj = {
                accessKeyId: res.data.accessKey,
                accessKeySecret: res.data.accessSecret,
                securityToken: res.data.token,
                region: "oss-" + res.data.regionId,
                bucket: res.data.bucket,
              };
            }
          });
          this.wangInit();
        }
      });
    },
    async submit() {
      this.form.content = this.editor.txt.html();
      if (this.form.title == "") {
        return this.$message.error("主题不能为空！");
      }
      if (this.form.content == "") {
        return this.$message.error("内容不能为空！");
      }
      if (this.form.type == 2 && this.form.ids == "") {
        return this.$message.error("指定用户ID不能为空！");
      }
      if (this.form.sendType == 2 && this.form.sendTime == "") {
        return this.$message.error("指定时间不能为空！");
      }
      console.log(this.form);
      const res = await AdminUnionPushMessage(this.form);
      if (res.code == 0) {
        this.$message.success("添加成功！");
        this.form = {
          title: "",
          content: "",
          type: "1",
          ids: "",
          sendType: "1",
          sendTime: "",
        };
        this.getList();
        this.dialogVisible = false;
      }
    },
    wangInit() {
      this.editor = new E("#websiteEditorElem");
      this.editor.config.uploadImgShowBase64 = true;
      this.editor.config.showLinkImg = false;
      this.editor.config.customUploadImg = (resultFiles, insertImgFn) => {
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后，插入到编辑器的方法
        let fileNames =
          "/img/" +
          Math.round(new Date() / 1000) +
          "." +
          resultFiles[0].name.substring(
            resultFiles[0].name.lastIndexOf(".") + 1
          );
        let cli = client(this.dataObj);
        let result = cli.multipartUpload(fileNames, resultFiles[0]);
        result
          .then(function (res) {
            // 上传图片，返回结果，将图片插入到编辑器中
            insertImgFn("https://img.psychexy.com" + fileNames);
          })
          .catch(function (err) {
            console.log(err);
          });
      };
      this.editor.create();
      this.editor.txt.html();
    },
    look(obj) {
      this.html = obj.content;
      this.dialogVisible1 = true;
    },
    nowSend(id) {
      this.$confirm(`是否立即发送`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await AdminUnionMessageSendUnionMessage({
            id,
          });
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.getList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    del(id) {
      this.$confirm(`是否删除`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await AdminUnionMessageDelUnionMessage({
            id,
          });
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.getList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
  },
  created() {
    this.getList();
  },
};
</script>

<style lang="less" scoped>
.UnionMessage {
  padding: 20px;
  .searchBox {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .el-input {
      width: 300px;
      margin-right: 10px;
    }
  }
  .dialog-footer {
    margin-top: 20px;
  }
}
</style>